/*
 * @Author: 高瑞寒 15932717091@163.com
 * @Date: 2022-05-08 23:07:44
 * @LastEditTime: 2022-05-16 10:19:02
 * @LastEditors: 高瑞寒 15932717091@163.com
 * @Description: 
 */
import React, { useState, useEffect } from 'react'
import { useSearchParams, useNavigate } from 'react-router-dom'
import { PageHeader, Button, Modal, Form, Input, message } from 'antd'

import Dayjs from 'dayjs'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
import { submitArticle, getArticleDetail, updateArticleDetail } from '@/api/article'

export default function Edit() {
  const navigate = useNavigate()
  const [searchParams] = useSearchParams()
  const id = searchParams.get('id')

  const [editor, setEditor] = useState() // 存储 editor 实例
  const [content, setContent] = useState() // 编辑器内容
  const [formData, setFormData] = useState({ title: '', subTitle: '' })
  const toolbarConfig = {}
  const editorConfig = {
    placeholder: '请输入内容...',
  }
  const showModal = () => {
    setVisible(true);
  };
  const handleCancel = () => {
    setVisible(false);
  };
  const [form] = Form.useForm();
  const [visible, setVisible] = useState(false);
  const onCreate = async ({ title, subTitle }) => {
    if (id) {
      const { message: msg
      } = await updateArticleDetail({ id, title, subTitle, content })
      message.success(msg)
      setVisible(false);
      navigate(-1)
    } else {
      const { message: msg } = await submitArticle({ title, subTitle, content })
      message.success(msg)
      setVisible(false);
    };
  }


  useEffect(() => {
    if (id) {
      getArticleDetail(id).then(res => {
        const { title, subTitle, content } = res.data
        setContent(content)
        setFormData({ title, subTitle })
      })
    }
  }, [id])

  return (
    <div>
      <PageHeader
        onBack={searchParams.get('id') ? () => navigate(-1) : false}
        title="编辑文章"
        subTitle={'当前日期:' + Dayjs(new Date()).format('YYYY-MM-DD')}
        extra={
          <Button key="3" type='primary' onClick={showModal}>提交文章</Button>}
      />
      <Toolbar
        editor={editor}
        defaultConfig={toolbarConfig}
        mode="default"
        style={{ borderBottom: '1px solid #ccc' }}
      />
      <Editor
        defaultConfig={editorConfig}
        value={content}
        onCreated={setEditor}
        onChange={editor => setContent(editor.getHtml())}
        mode="default"
        style={{ height: '500px', 'overflowY': 'hidden' }}
      />
      <Modal title="填写文章标题"
        visible={visible}
        onOk={() => {
          form
            .validateFields()
            .then(values => {
              form.resetFields();
              onCreate(values);
            })
            .catch(info => {
              console.log('Validate Failed:', info);
            });
        }}
        onCancel={handleCancel}
        okText="确认"
        cancelText="取消">
        <Form
          form={form}
          name="form_in_modal"
          initialValues={{
            title: formData.title, subTitle: formData.subTitle
          }}

          autoComplete="off"
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请填写标题' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="副标题"
            name="subTitle"
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div >
  )
}
